<template>
  <c-dialog ref="dialog" :title="text" :open-fun="openFun">
    <c-list ref="form" :model="formData" :rules="formRules">
      <c-list-item prop="fileList">
        <div class="files-container">
          <el-form :inline="true" :model="formInline">
            <el-form-item :rules="[{ required: true,message:'请选择审核意见', trigger: 'change' }]" label="审核意见：">
              <el-radio-group v-model="formInline.isAgree" @change="changeAgree">
                <el-radio :label="1">同意</el-radio>
                <el-radio :label="0">不同意</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <c-file-list v-model="formData.fileList" type-code="ACCESS018" :limit="1" title="单个合同上传" />
        </div>
      </c-list-item>
      <c-list-item>
        <div class="btn-container">
          <c-button @click="cancelHandle">取消</c-button>
          <c-button type="primary" @click="saveHandle">保存</c-button>
        </div>
      </c-list-item>
    </c-list>
  </c-dialog>
</template>
<script>
import { uploadContract, postChangeContract } from '@/api/decorate'
import { postConfigAttachmentTemplate, getBatchFile } from '@/api/common'
import { otherFiltersItem } from '@/utils'
export default {
  name: 'SingleContract',
  components: {
  },
  props: {
    selData: {
      type: Array,
      default: () => []
    },
    change: {
      type: Boolean,
      default: false
    },
    // 走变更接口，去掉某些校验
    uploadNoChange: {
      type: Boolean,
      default: false
    },
    text: {
      type: String,
      default: '单个合同上传'
    }
  },
  data() {
    const validatorFiles = (r, v, c) => {
      if (this.$getFiles(v, this.selData[0].id).filter(e => e.dr !== 1 && e.dr !== '1').length === 0) {
        c(new Error('请上传合同'))
      } else {
        c()
      }
    }
    return {
      formInline: {
        isAgree: 1
      },

      formData: {
        fileList: []
      },
      formRules: {
        fileList: [{ required: true, validator: validatorFiles, trigger: 'change' }]
      },
      // 合同附件模板
      configFileId: ''
    }
  },
  created() {
    if (this.change) {
      this.getFileConfig()
    }
  },
  methods: {
    changeAgree(data) {
      if (!data) { this.$refs.form.clearValidate() }
    },
    // 获取配置
    getFileConfig() {
      const data = new FormData()
      data.append('pageFlag', false)
      const filtersRaw = [
        otherFiltersItem('typeCode', 'ACCESS018', '=')
      ]
      data.append('filtersRaw', JSON.stringify(filtersRaw))
      postConfigAttachmentTemplate(data).then(res => {
        this.configFileId = res.data.records[0].id
      })
    },
    checkFile(ids) {
      return getBatchFile(ids).then(res => {
        const hasIds = new Set()
        for (const item of res.data.records) {
          if (item.configAttachmentId === this.configFileId) {
            hasIds.add(item.modelId)
          }
        }
        if (ids.every(id => hasIds.has(id))) {
          return true
        }
        const t = this.selData.filter(e => !hasIds.has(e.id)).map(e => e.decorationTaskCode).join(',')
        this.$message.warning(`${t}没有上传合同！`)
        return Promise.reject(false)
      })
    },
    openFun() {
      // if (!this.change && this.selData.length !== 1) {
      //   this.$message.warning('请选择一条数据！')
      //   return false
      // }
      if (this.selData.length === 0) {
        this.$message.warning('请选择数据！')
        return false
      }
      let flag
      for (const item of this.selData) {
        if (item.constUnitCode === undefined) {
          this.$message.warning('没有施工单位')
          return false
        }
        const t = `${item.constUnitCode}-${item.shopCode}`
        if (flag === undefined) {
          flag = t
        }

        if (flag !== t) {
          this.$message.warning('只能选择同门店、同施工单位的不同装修任务！')
          return false
        }
      }
      if (this.uploadNoChange) {
        return true
      }
      if (this.change) {
        const ids = this.selData.map(e => e.id)
        return this.checkFile(ids)
      }
      return true
    },
    upload() {
      let data = this.$getFiles(this.formData.fileList, this.selData[0].id).filter(e => e.dr !== 1 && e.dr !== '1')
      if (!this.change && !this.uploadNoChange) {
        const t = data[0]
        data = this.selData.map(e => {
          const m = { ...t }
          m.modelId = e.id
          return m
        })
        const commitForm = { shopAttachmentDTOS: data, decorationTaskCode: this.selData[0].decorationTaskCode, isAgree: this.formInline.isAgree }
        return uploadContract(commitForm).then(res => {
          this.$message.success('操作成功！')
          this.$emit('on-success')
          this.$refs.dialog.visible = false
        })
      } else {
        delete data.modelId
        return postChangeContract({
          dtoList: this.selData,
          files: data
        }).then(res => {
          this.$message.success('操作成功！')
          this.$emit('on-success')
          this.$refs.dialog.visible = false
        })
      }
    },
    async  saveHandle() {
      if (!this.formInline.isAgree) {
        this.$refs.form.clearValidate()
        this.upload()
      } else {
        const data = await this.$refs.form.validate()
        if (data) {
          this.upload()
        }
      }
    },
    cancelHandle() {
      this.$refs.dialog.visible = false
    }
  }
}
</script>
<style lang="scss" scoped>
.files-container{
  /deep/ .c-upload-slot{
    text-align: left;
  }
}
</style>
